package br.com.JZSolution.domineduplex.gui;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSplitPane;

import br.com.JZSolution.domineduplex.DomineDuplex;
import br.com.JZSolution.domineduplex.controle.ControladorDeUsuario;
import br.com.JZSolution.domineduplexserver.modelo.Comunicador;
import br.com.JZSolution.domineduplexserver.modelo.Usuario;

public class MainFrame extends JFrame{
	
	private static final long serialVersionUID = 1L;
	private TransfersPanel transferPanel;
	private PainelContatos painelContatos;
	private PainelDeBotoes painelDeBotoes;
	private PainelDeStatus painelStatus;
	
	public MainFrame(){
		this.setJMenuBar(new Menu());
		this.setLayout(new BorderLayout());
		transferPanel = new TransfersPanel();
		painelContatos = new PainelContatos();

		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
		splitPane.setDividerLocation(200);
		splitPane.add(painelContatos);
		
		painelStatus = new PainelDeStatus();
		painelDeBotoes = new PainelDeBotoes();
		splitPane.add(transferPanel);
		
		this.setTitle("Domine Duplex");
		this.add(painelDeBotoes,BorderLayout.NORTH);
		this.add(splitPane,BorderLayout.CENTER);
		this.add(painelStatus, BorderLayout.SOUTH);
		this.pack();
		this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/Conectado.png")));
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		this.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e) {
				DomineDuplex.getInstance().salvarPreferencias();
			}
			
			@Override
			public void windowClosed(WindowEvent e) {
				Usuario user = DomineDuplex.getInstance().getUsuarioAutenticado();
				if(user != null){
					Thread timeoutLogoff = new Thread(){
						public void run() {
							while(true){
								try {
									Thread.sleep(10000);
									System.out.println("Encerrando por timeout do server");
									System.exit(0);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}
						};
					};
					timeoutLogoff.start();
					ControladorDeUsuario.getInstance().comunicarComServidor(ControladorDeUsuario.SAIR, user.propriedades());
				}
				System.exit(0);
			}
		});
		
	}
	
	public PainelContatos getPainelContatos() {
		return painelContatos;
	}
	public TransfersPanel getTransferPanel() {
		return transferPanel;
	}
	public JLabel getStatusLbl() {
		return painelStatus.getStatusLbl();
	}
	public PainelDeBotoes getPainelDeBotoes(){
		return painelDeBotoes;
	}
}
